import * as monaco from 'monaco-editor'

import BwMonacoEditor from '@/utils/monacoEditor'
import { useComDesignStoreWithOut } from '@/store'
import { ref, unref, toRaw, nextTick, watch, onBeforeUnmount } from 'vue'

const defaultStyle = `/**
* 温馨提示：在这里编写你的页面样式。
* 你可以点击面板上方的「使用帮助」了解。
*/
`

export function useComCss(emit) {
  const bwMonacoEditor = new BwMonacoEditor()
  const designStore = useComDesignStoreWithOut()

  const cssEdit = ref()
  const curValue = ref<string>()
  const isMax = ref<boolean>(false)
  const curEditor = ref<monaco.editor.IStandaloneCodeEditor | undefined>()

  const onSize = (is: boolean) => {
    isMax.value = is
  }

  const onClose = () => emit('close')

  /** 获取当前逻辑信息 */
  const getValue = (): string => {
    let value = ''
    const curEdit = unref(curEditor)
    if (curEdit) {
      value = toRaw(curEdit).getValue()
    }
    return value
  }

  const initMonacoEditor = () => {
    const value = designStore.getComCss ?? defaultStyle

    curValue.value = value
    curEditor.value = bwMonacoEditor.create({
      domElement: cssEdit.value,
      options: {
        value: value,
        wordWrap: 'on',
        language: 'css',
      },
      menus: undefined,
      snippets: undefined,
    })

    /** 监听编辑器内容变化 */
    const curEdit = unref(curEditor)
    if (curEdit) {
      curEdit.onDidChangeCursorPosition(function (e) {
        if (curEdit) {
          let readOnly = false
          if (e.position.lineNumber < 4) {
            readOnly = true
          }
          toRaw(curEdit).updateOptions({
            readOnly: readOnly,
          })
        }
      })

      curEdit.onDidChangeModelContent(() => {
        try {
          const curText = getValue()
          if (curText) {
            curValue.value = curText
            designStore.setDesignComCss(curText)
          }
        } catch (error) {
          console.warn('编辑器报错')
        }
      })
    }
  }

  onBeforeUnmount(() => {
    /** 编辑器关闭前保存内容 */
    designStore.setDesignComCss(unref(curValue) ?? '')
    bwMonacoEditor.dispose()
  })

  watch(
    () => designStore.curFrontType,
    () => {
      nextTick(() => {
        initMonacoEditor()
      })
    },
    { deep: true, immediate: true }
  )
  return { isMax, cssEdit, onSize, onClose }
}
